# -*- coding: utf-8 -*-
import base64
import io
import json
import time

from PIL import Image
from django.http import HttpResponse, JsonResponse
from django.http import HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt

from apps.api.mapper.sql_connect import verify_user_login, register_user, del_user_data, modify_user_data
from apps.api.service.detect_api import image_detect


@csrf_exempt
def img_api(request):
    if request.method == 'POST' and request.body:
        body = request.body.decode('utf-8')  # 将字节流解码为字符串

        data = json.loads(body)  # 将JSON格式的字符串解析为Python字典
        image_base64 = data['image']

        # 解码base64字符串
        image_data = base64.b64decode(image_base64)
        filepath = r"./media/image.png"

        # 使用PIL库将二进制数据转换为图像对象
        image = Image.open(io.BytesIO(image_data))

        with open(filepath, "wb") as file:
            image.save(file, "png")
        time.sleep(1)

        # 开始识别行为
        save_path, probs, position, name = image_detect("./media/image.png")
        if save_path != "no detection":
            # 读取图像文件
            with open(save_path, 'rb') as f:
                image_data = f.read()

            # 将图像数据转换为base64编码
            image_base64 = base64.b64encode(image_data).decode('utf-8')

            # 构建响应对象
            response = HttpResponse(content_type='application/json')

            response_data = {
                'code': 1,
                'message': "success",
                'image': image_base64,
                'probs': probs,
                'position': position,
                'name': name
            }

            # 将图像的Base64编码作为响应的内容
            response.write(json.dumps(response_data))

            return response
        else:
            # 返回错误的响应
            return HttpResponse("没有检测到鸟类")
    # 返回错误的响应
    return HttpResponseBadRequest("未上传图片或使用了无效的请求方法")


# 登录逻辑
@csrf_exempt
def login(request):
    form = json.loads(request.body)
    print(form)
    if form:
        # 登录校验
        result = verify_user_login(form['username'], form['password'], form['status'])
        if result:
            code = 1
            message = "登录成功。"

        else:
            code = 0
            message = "登录失败，请检查身份或用户名与密码是否匹配。"
    else:
        # 没有接收到数据
        code = 0
        message = "没有接收到数据"
    response = {
        'code': code,
        'message': message
    }
    return JsonResponse(response)


# 注册逻辑
@csrf_exempt
def register(request):
    form = json.loads(request.body)

    if form['status'] == 0:
        status = "user"
    else:
        status = "manager"
    if form:
        # 登录校验
        result = register_user(form['username'], form['password'], status)
        if result:
            code = 1
            message = "注册成功。"
        else:
            code = 0
            message = "注册失败，用户名已经存在"
    else:
        # 没有接收到数据
        code = 0
        message = "没有接收到数据"
    response = {
        'code': code,
        'message': message
    }
    return JsonResponse(response)


# 删除用户
@csrf_exempt
def del_user(request):
    username = json.loads(request.body)['username']
    result = del_user_data(username)
    if result:
        response = {
            'code': 1,
            'message': "success",
            "data": f"删除用户{username}成功，请刷新页面查看"
        }
        return JsonResponse(response)


# 修改用户信息
@csrf_exempt
def modify_user(request):
    form = request.POST.dict()
    username = form['edit-username']
    password = form['edit-password']
    status = form['edit-status']
    result = modify_user_data(username, password, status)
    if result:
        response = {
            'code': 1,
            "message": "success",
            "data": "修改成功，请刷新页面查看数据。"
        }
        return JsonResponse(response)


# 新增用户
@csrf_exempt
def add_user(request):
    form = request.POST.dict()
    if form:
        # 登录校验
        result = register_user(form['username'], form['password'], form['status'])
        if result:
            code = 1
            message = "注册成功。"
        else:
            code = 0
            message = "注册失败，用户名已经存在"
    else:
        # 没有接收到数据
        code = 0
        message = "没有接收到数据"
    response = {
        'code': code,
        'message': message
    }
    print(response)
    return JsonResponse(response)
